<template>
<!-- <h2>物品管理</h2> -->
  <div class="goods-main" v-loading="loading">
    <div class="goods-content">
      <div class="left-area">
        <div class="area-search">
          <el-input
            v-jurisdiction="'pay:item:getItemPage'"
            placeholder="筛选项目类型"
            class="input-6"
            v-model="treeSearch"

            >
            <template #prefix>
              <el-icon><search /></el-icon>
            </template>
          </el-input>
        </div>
        <div class="area-tree">
          <div class="all-goods">全部项目</div>
          <el-tree
            class="tree-height"
            ref="treeRef"
            default-expand-all
            :props="defaultProps"
            :data="treeData"
            :load="loadNode"
            @node-click="handleNode"
            @node-contextmenu="handleNodeMenu"
            :filter-node-method="filterNode"
            >
          </el-tree>
            <div class="add-goods">
              <span @click="addProject('root')" v-jurisdiction="'pay:item:type:add'">
                <el-icon><plus /></el-icon>
                <span>添加收费项目类型</span>
              </span>
            </div>
    
        </div>
      </div>
      <div class="right-area">
        <div class="right-area-search">
          <el-input
            v-jurisdiction="'pay:item:getItemPage'"
            placeholder="项目名称/常用名/品牌"
            class="input-6"
            v-model="searchName"
            @keydown.enter="hanledSearch"
            >
            <template #prefix>
              <el-icon><search /></el-icon>
            </template>
          </el-input>

          <el-button class="btn-2" @click="refrechList" >刷新</el-button>
          <el-button class="btn-2" @click="cancelSelectProject" >取消选中项目</el-button>
          <el-button class="btn-2" @click="handleClickDrawer" v-jurisdiction="'pay:item:add'">新增收费项目</el-button>
        </div>
        <div class="table">
          <ztable 
            :tableData='data' 
            :strucs='groupData'
            :header-cell-style="{background:'#11b9d0', color:'#fff'}"
            :height="'100%'"
            :width="'300'"
            :isshowOperation="true"
          >
            <template #default="slotScope">
              <el-button type="text" class="operation" @click="handleReturn(slotScope.rowData)" v-jurisdiction="'pay:item:setting:setVisitSetting'" >回访</el-button>
              <el-button type="text" class="operation" @click="handleEditItem(slotScope.rowData)" v-jurisdiction="'pay:item:update'">修改</el-button>
              <el-button type="text" class="operation" @click="handleDelItem(slotScope.rowData, slotScope.index)" v-jurisdiction="'pay:item:del'">删除</el-button>
            </template>
          </ztable>
        </div>
        <div class="page">
            <zpage 
              :currentPage="current" 
              :total="total" 
              :pageSize="size"
              @handleSizeChange="handleSizeChange" 
              @handleCurrentChange="handleCurrentChange"
          ></zpage>
        </div>
      </div>
    </div>
  
  </div>

  <!-- 右击提示操作框 -->
  <div class="tipsOperation" ref="tipsOPerRef" v-show="menuVisbile">
    <div class="tip-item" @click="addProject('children') ">
      <el-icon><edit /></el-icon>
      <span>添加子类型</span>
    </div>
    <div class="tip-item" @click="edit" v-jurisdiction="'pay:item:type:update'">
      <el-icon><edit /></el-icon>
      <span>修改</span>
    </div>
    <div class="tip-item" @click="remove" v-jurisdiction="'pay:item:type:del'">
      <el-icon><delete /></el-icon>
      <span>删除</span>
    </div>
  </div>
  <!-- 新增 -->
  <zdrawer size="40%" @handleClose="drawerClose('add')" title="新增收费项目" v-model="showDrawer" >
    <template #body>
    <!-- 动态 -->
    <ztitleBorder title="基础信息">
      <div class="dynamic flex-wrap">
        <component :is="showWidget(item.type)" class="test" v-for="item in groupDataAdd" :key="item.name" :struc="item" :passWidth="50"  />
      </div>
    </ztitleBorder>
    </template>
    <template #footer>
      <el-button class="btn-2" @click="cancel('add')">取消</el-button>
      <el-button class="btn-1" @click="save('add')">保存</el-button>
    </template>
  </zdrawer>

  <!-- 修改 -->
  <zdrawer size="40%" @handleClose="drawerClose('edit')" title="修改物品" v-model="showEditDrawer" >
    <template #body>
    <!-- 动态 -->
    <ztitleBorder title="基础信息">
      <div class="dynamic flex-wrap">
        <component :is="showWidget(item.type)" class="test" v-for="item in groupDataUpdate" :key="item.name" :struc="item" :passWidth="50"  />
      </div>
    </ztitleBorder>
    </template>
    <template #footer>
      <el-button class="btn-2" @click="cancel('edit')">取消</el-button>
      <el-button class="btn-1" @click="save('edit')">保存资料</el-button>
    </template>
  </zdrawer>

  <zdialog :title="titleType" @handleClose="closeDialog" v-model="dialogVisible" :btnData="dialogBtnData">
    <template #body>
      <div class="flex-wrap">
        <div class="leftToRight-layout" style="width: 100%">
          <div class="label">
            <span>类型名称</span>
          </div>
          <div class="operations">
            <el-input  v-model="name" ></el-input>
          </div>
        </div>
        <div class="leftToRight-layout" style="width: 100%" v-show="!Boolean(typeId)">
          <div class="label">
            <span>分类类型</span>
          </div>
          <div class="operations">
            <el-select v-model="itemType"  placeholder="请选择" clearable>
            <el-option
              v-for="item in modelOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          </div>
        </div>
      </div>
      
    </template>
</zdialog>

<!-- 回访设置 -->
<zdialog title="回访设置" @handleClose="closeReturnDialog" v-model="dialogReturnVisible" :btnData="dialogReturnBtn">
    <template #body>
      <el-table
          :data="returnSysList"
          border
          style="width: 100%"
          height="300"
          >
          <el-table-column prop="numberOfTimes" label="次数" width="60"></el-table-column>
          <el-table-column
            prop="intervals"
            label="	与上次间隔时间（天）"
            >
            <template #default="scope">
              <el-input-number  v-model="scope.row.intervals" :min="1" class="input-2"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column
            prop="content"
            label="内容"
            >
            <template #default="scope">
            <el-input placeholder="请输入内容" v-model="scope.row.content"  class="input-2"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            align="right">
            <template #header>
              <el-button class="btn-1" @click="addProcess">新增</el-button>
            </template>
            <template #default="scope">
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      
    </template>
</zdialog>
</template>

<script lang='ts'>
import { Plus, Delete, Edit, Search } from '@element-plus/icons-vue'
import { defineComponent, reactive, ref, toRefs, watch, onUnmounted } from '@vue/runtime-core'
import ztable from '@components/Table/index.vue'
import zpage from '@components/pagination/pagination.vue'
import zsearch from '@components/search/search.vue'
import zdrawer from "@components/drawer/drawer.vue";
import ztitleBorder from "../../../components/titleBorder/titleBorder.vue"
import ztree, {NodeChildren} from "../../../components/tree/tree.vue"
import zdialog from '@components/dialog/dialog.vue'

import useShowWidget from "../../../components/widget/usechoose";

import useConfgin from '../../../hook/getconfig'
import useUser from "../../../hook/user";
import useRequet, { RespData } from "./../../../hook/network"
import useDataCheck, { DataStruc } from "./../../../hook/datastruc";
import {Option} from "../../../types/index"

import { addPayItemApi, updatePayItemApi } from "../../../api/payservice"


import { useRouter } from "vue-router"
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'

const configID = 548;
export default defineComponent({
name: 'PayService',
components: {
  ztable,
  zpage,
  zsearch,
  zdrawer,
  ztitleBorder,
  ztree,
  zdialog,

  Plus, Delete, Edit, Search
},
setup() {
  const router = useRouter();
  const dataCheck = useDataCheck();
  const request = useRequet({ path: "" });
  const rowList = useConfgin(configID)
  console.log('收费项目', rowList)
    /** 列表部分 -> 开始 */
  let search = reactive({
    date:'',
    current: 1,
    size: 100,
    total: 0,
    id: null,
    loading: false,
    searchName: ''
  })
  const data = ref([])
  const MackData = ref([])
  const AddList = ref([] as DataStruc[])
  const groupData = rowList.groupDataList.value;
  
  const groupDataAdd = ref([
    {
          id: 582,
          name: "itemName",
            viewName: "项目名称",
            type: 102,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "请输入项目名称",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 1,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: 0,
            idName: null
    },
    {
          id: 582,
          name: "nickname",
            viewName: "昵称",
            type: 102,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 0,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 1,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: 0,
            idName: null
    },
    {
          id: 582,
          name: "specification",
            viewName: "规格",
            type: 102,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 0,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 1,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: 0,
            idName: null
    },
    {
          id: 582,
          name: "unit",
            viewName: "单位",
            type: 102,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 0,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 1,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: 0,
            idName: null
    },
    {
          id: 582,
          name: "brand",
            viewName: "品牌",
            type: 102,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 0,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 1,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: 0,
            idName: null
    },
    {
          id: 582,
          name: "realPrice",
            viewName: "价格",
            type: 102,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 0,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 1,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: 0,
            idName: null
    },
    {
          id: 582,
          name: "imageUrl",
            viewName: "图片",
            type: 666,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 0,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 1,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: 0,
            idName: null
    },
    {
          id: 582,
          name: "remark",
            viewName: "备注",
            type: 103,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 0,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 1,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: 0,
            idName: null
    },
  ])
  
  const groupDataUpdate = ref([
    {
          id: 582,
          name: "itemName",
            viewName: "项目名称",
            type: 102,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "请输入项目名称",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 1,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: 0,
            idName: null
    },
    {
          id: 582,
          name: "nickname",
            viewName: "昵称",
            type: 102,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 0,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 1,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: 0,
            idName: null
    },
    {
          id: 582,
          name: "specification",
            viewName: "规格",
            type: 102,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 0,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 1,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: 0,
            idName: null
    },
    {
          id: 582,
          name: "unit",
            viewName: "单位",
            type: 102,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 0,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 1,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: 0,
            idName: null
    },
    {
          id: 582,
          name: "brand",
            viewName: "品牌",
            type: 102,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 0,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 1,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: 0,
            idName: null
    },
    {
          id: 582,
          name: "realPrice",
            viewName: "价格",
            type: 102,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 0,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 1,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: 0,
            idName: null
    },
    {
          id: 582,
          name: "imageUrl",
            viewName: "图片",
            type: 666,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 0,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 1,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: 0,
            idName: null
    },
    {
          id: 582,
          name: "remark",
            viewName: "备注",
            type: 103,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 0,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 1,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: 0,
            idName: null
    },
  ])
  
  onUnmounted(() => {
    dataCheck.clearDataCheck();
  });
  // 分页
  const handleCurrentChange = (val: number) => {
    search.current = val
    req()
  }
  const handleSizeChange = (val: number) => {
    search.size = val
    req()
  }



  const refrechList = () => {
    req()
  }
  const cancelSelectProject = () => {
    console.log('取消选中项目')
    tree.typeId = 0
    filterProjectList()
  }

  //搜索
  const hanledSearch = () => {
    req()
  }

  /** 列表部分 -> 结束 */

  /** 物品分类树 */
  const tree = reactive({
    treeData: [],
    treeSearch: '',
    typeId: 0
  })

    const req = () => {
    search.loading = true;
    
    let params = {
      current: search.current,
      size: search.size,
      name: search.searchName,
    } as any
    if(tree.typeId) {
      params.typeId = tree.typeId
    }
    request.sendRequest({
      address: 'pay/item/getItemPage',
      params,
      success: (resp: RespData) => {
        if(resp.code !== 0) return ElMessage.error('获取收费项目列表' + resp.msg)
        data.value = resp.data.records || []
        MackData.value = resp.data.records || []
        search.total = resp.data.total
        search.size = resp.data.size
        search.current = resp.data.current

        search.loading = false
      },
      fail: (resp: RespData) => {
        if(resp.code !== 0) return ElMessage.error('获取收费项目列表' + resp.msg)
        search.loading = false
      },
      method: "POST",
    })
}
  req()

  const defaultProps = {
    children: 'children',
    label: 'name',
    isLeaf: 'leaf'
  }

  const getTreeList = () => {
    request.sendRequest({
      address: 'pay/item/typeTree',
      params: {},
      success: (resp: RespData) => {
        if(resp.code !== 0) return ElMessage.error(resp.msg || '获取收费项目分类树形图失败')
        tree.treeData = resp.data
      },
      fail: (resp: RespData) => {
        if(resp.code !== 0) return ElMessage.error(resp.msg || '获取收费项目分类树形图失败')
        
      },
      method: "GET",
    })
  }
  getTreeList()

  const treeRef: any = ref(null)
  watch(() => tree.treeSearch, (newV, preV) => {
    treeRef.value.filter(newV)
  } )
  // 筛选树
  const filterNode = (val: string, data: any) => {
    if (!val) return true;
    return data.name.indexOf(val) !== -1;
  }


  const handleNode = (data: any, node: any) => {

    
    menuVisbile.value = false
    isNodeActive.value = data.id

    tree.typeId = data.id
    orderNum.value = data.orderNum
    parentId.value = data.superId

    filterProjectList()
  }

  const filterProjectList = () => {
    req()
    // data.value = MackData.value
    // if(id) {
    //   data.value = data.value.filter((item:any) => item.typeId == id)
    // } else {
    //   data.value = MackData.value
    // }

    // search.total = data.value.length
  }

  const tipsOPerRef = ref<HTMLElement | null>(null)
  const menuVisbile = ref(false)
  // 点击某一节点右击事件
  const handleNodeMenu = (e: MouseEvent, obj: any, node: any) => {
    name.value = obj.name

    tree.typeId = obj.id
    orderNum.value = obj.orderNum
    parentId.value = obj.superId

    menuVisbile.value = true
    // 获取鼠标右击的 x, y 坐标
    let x = e.clientX;
    let y = e.clientY;
    (tipsOPerRef.value as HTMLElement).style.top = y + 10 +  'px';
    (tipsOPerRef.value as HTMLElement).style.left = x + 20 + 'px';

  }

  const loadNode = (node:any, resolve: Function) => {
    console.debug(node, resolve)
  }


  const dialogVisible = ref(false)
  const isNodeActive = ref('')
  const name = ref('')
  const parentId = ref('')
  const orderNum = ref('')
  const itemType = ref()
  const modelOptions = ref([] as Option[])

  const getModelOptions = () => {
    request.sendRequest({
        address: `pay/item/getItemTypeSelect`,
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error('获取类型' + resp.msg)
          modelOptions.value = resp.data
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error('获取类型' + resp.msg)
        },
        method: "GET",
      })
  }
  getModelOptions()

  const titleType = ref('添加付款项目类型')
  
  const addProject = (type: string) => {
    menuVisbile.value = false
    dialogVisible.value = true
    name.value = ''

    if(type === 'root') {
      // 根类型
      titleType.value = '添加付款项目类型'
      tree.typeId = 0
    }

    if(type === 'children') {
      titleType.value = '添加付款项目子类型'
      // 子类型
    }
  }
  // 修改大项
  const edit = () => {
    menuVisbile.value = false
    titleType.value = '修改付款项目类型'
    dialogVisible.value = true
  }
  // 删除大项
  const remove = () => {
    menuVisbile.value = false

    ElMessageBox.confirm(`此操作将永久删除【${name.value}】, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          request.sendRequest({
            address: `pay/item/delType/${tree.typeId}`,
            params: {},
            success: (resp: RespData) => {
              if(resp.code !== 0) return ElMessage.error(resp.msg || '删除失败')
              
              menuVisbile.value = false
              ElMessage.success('删除成功')
              // children.splice(index, 1)
              getTreeList()
            },
            fail: (resp: RespData) => {
              if(resp.code !== 0) return ElMessage.error(resp.msg || '删除失败')
            },
            method: "POST",
          })
        }).catch(() => {
          ElMessage({
            type: 'info',
            message: '已取消删除',
          });
        })
      
  }

  const closeDialog = () => {
    name.value = ''
    dialogVisible.value = false
  }

  const dialogBtnData = [
    {
      name: '取消',
      func: (data:object) => {
        console.debug('取消',JSON.parse(JSON.stringify(data)))
        dialogVisible.value = false
      }
    },
    {
      name: '保存',
      func: (data:object) => {
        console.debug('保存',JSON.parse(JSON.stringify(data)))
          menuVisbile.value = false
          if(titleType.value === '添加付款项目类型' || titleType.value === '添加付款项目子类型') {
              addTypeTree()
          }
          if(titleType.value === '修改付款项目类型') {
            editTypeTree()
          }
          
      }
    }
  ]

  const addTypeTree = () => {
    addTypeTreeInterface()
  }

  // 添加项目类型接口
  const addTypeTreeInterface = () => {
    request.sendRequest({
      address: 'pay/item/addType',
      params: {
        name: name.value,
        itemType: itemType.value,
        superId: tree.typeId
      },
      success: (resp: RespData) => {
        if(resp.code !== 0) return ElMessage.error('添加收费大项' + resp.msg)
        ElMessage.success('添加收费项目' + resp.msg)
        closeDialog()
        req()
        getTreeList()
      },
      fail: (resp: RespData) => {
        if(resp.code !== 0) return ElMessage.error('添加收费大项' + resp.msg)
        
      },
      method: "POST",
    })
  }

  const editTypeTree = () => {
    request.sendRequest({
      address: 'pay/item/updateTypeInfo',
      params: {
        name: name.value,
        superId: parentId.value,
        id: tree.typeId,
        orderNum: orderNum.value
      },
      success: (resp: RespData) => {
        if(resp.code !== 0) return ElMessage.error('修改收费大项' + resp.msg)
        ElMessage.success('修改收费项目' + resp.msg)
        menuVisbile.value = false
        closeDialog()
        req()
        getTreeList()

      },
      fail: (resp: RespData) => {
        if(resp.code !== 0) return ElMessage.error('修改收费大项' + resp.msg)
        
      },
      method: "POST",
    })
  }


  /** 抽屉部分开始 */
  const showWidget = useShowWidget;
  let showDrawer = ref(false)
  let showEditDrawer = ref(false)

  const handleClickDrawer = () => {
    if(!tree.typeId) {
      showDrawer.value = false
      // 提示
      ElMessage.warning('请选择左侧项目, 在点击新增')
    } else {
      showDrawer.value = true
      
    }
    
    
  }

  const drawerClose = (type:string) => {
    if(type === 'add') {
      showDrawer.value = false
      groupDataAdd.value.map(item => item.value = '')
    } else if (type === 'edit') {
      showEditDrawer.value = false
    }
    tree.typeId = 0
  }
  const cancel = (type:string) => {
    if(type === 'add') {
      showDrawer.value = false
    } else if (type === 'edit') {
      showEditDrawer.value = false
    }
  }

  // 回访设置
  const handleReturn = (rowData: any) => {
    projectItemId.value = rowData.id
    getReturnSysList()
    dialogReturnVisible.value = true
  }

  // 修改
  const handleEditItem = (rowData: any) => {
    showEditDrawer.value = true
    tree.typeId = rowData.typeId
    search.id = rowData.id
    groupDataUpdate.value.forEach((item: any) => {
        Object.keys(rowData).forEach(i => {
          if(item.name === i) {
          item.value = rowData[item.name]
        }
      })
    })
  }

  // 删除
  const handleDelItem = (rowData: any, index: number) => {
    let id = rowData.id
      ElMessageBox.confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        request.sendRequest({
          address: `pay/item/delItem/${id}`,
          params: {},
          success: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg || '删除失败')
            ElMessage.success('删除成功')
            req()
          },
          fail: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg || '删除失败')
          },
          method: "POST",
        })
      }).catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消删除',
        });
      })
  }


  // 回访设置
  type ReturnSys = {
    intervals: string | number,
    content: string
  }
  const dialogReturnVisible = ref(false)
  const returnSysList = ref([] as ReturnSys[])
  const projectItemId = ref('')
  const closeReturnDialog = () => {
    dialogReturnVisible.value = false
    returnSysList.value = []
  }
  const dialogReturnBtn = [
    {
      name: '取消',
      func: (data:any) => {
        console.debug('取消',JSON.parse(JSON.stringify(data)))
        closeReturnDialog()
      }
    },
    {
      name: '保存',
      func: (data:any) => {
        console.debug('保存',JSON.parse(JSON.stringify(data)))
        if(projectItemId.value) {
          request.sendRequest({
            address: '/pay/item/setting/setVisitSetting',
            params: {
              itemId: projectItemId.value,
              list: returnSysList.value
            },
            success: (resp: RespData) => {
              if(resp.code !== 0) return ElMessage.error('回访设置' + resp.msg)
              ElMessage.success('回访设置' + resp.msg)
              closeReturnDialog()
            },
            fail: (resp: RespData) => {
              if(resp.code !== 0) return ElMessage.error('回访设置' + resp.msg)
            },
            method: "POST",
          })
        }
      }
    },
  ]

  const getReturnSysList = () => {
    let itemId = projectItemId.value
    request.sendRequest({
        address: `/pay/item/setting/getVisitSetting/${itemId}`,
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error('获取回访设置列表' + resp.msg)
          returnSysList.value = resp.data
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error('获取回访设置列表' + resp.msg)
        },
        method: "POST",
      })
  }
  const addProcess = () => {
    returnSysList.value.push({
      intervals: 10,
      content: ''
    })
  }
  const handleDelete = (index: number) => {
    returnSysList.value.splice(index, 1)
  }

  const save = async(type:string) => {
    let params = {} as any 

    if(!dataCheck.checkAll()) {
      return false
    }
    if(type === 'add') {
        groupDataAdd.value.forEach(item => {
          params[item.name] = item.value
        })
        params.typeId = tree.typeId

        let resp:any = await addPayItemApi(params)
        if(resp.code !== 0) return ElMessage.error('新增收费项目' + resp.msg)
        ElMessage.success('添加成功')
        showDrawer.value = false
        groupDataAdd.value.map(item => item.value = '')
        tree.typeId = 0
        req()
      
    } else if (type === 'edit') {
      groupDataUpdate.value.forEach(item => {
          params[item.name] = item.value
      })
      params.typeId = tree.typeId
      params.id = search.id

      let resp:any = await updatePayItemApi(params);
      if(resp.code !== 0) return ElMessage.error(resp.msg || '修改失败');
      ElMessage.success('修改成功')
      req()
      showEditDrawer.value = false
      
    }

  }
  /** 抽屉部分结束 */
  return {
    ...toRefs(search),
    data,

    AddList,
    hanledSearch,
    handleCurrentChange,
    handleSizeChange,
    handleReturn,
    handleEditItem,
    handleDelItem,

    filterNode,
    treeRef,

    groupData,
    groupDataAdd,
    groupDataUpdate,
    ...toRefs(tree),
    defaultProps,
    handleNode,

    cancelSelectProject,

    handleNodeMenu,
    tipsOPerRef,
    menuVisbile,

    refrechList,


    showDrawer,
    showEditDrawer,
    showWidget,
    handleClickDrawer,
    drawerClose,
    cancel,
    save,

    edit,
    remove,
    loadNode,
    dialogVisible,
    isNodeActive,
    titleType,
    name,
    closeDialog,
    dialogBtnData,
    addProject,
    itemType,
    modelOptions,

    dialogReturnVisible,
    closeReturnDialog,
    dialogReturnBtn,
    returnSysList,
    projectItemId,
    addProcess,
    handleDelete,

  }
}
})
</script>

<style lang="scss" scoped>
.goods-main {
width: 100%;
height: 100%;
background: white;
.goods-head {
  height: 40px;
  line-height: 40px;
  text-align: right;
  padding-right: 20px;
}
.goods-content {
  display: flex;
  padding: 10px 20px;
  height: calc(100% - 50px);
  box-sizing: border-box;
  .left-area {
    background: white;
    box-shadow: 2px 2px 5px rgba(233, 230, 230 ,.8), -2px -2px 5px rgba(233, 230, 230 ,.8);
    border-radius: $radius-1;
    margin-right: 10px;
    position: relative;
    .area-search {
      padding-left: 5px;
      padding-top: 10px;
    }
    .area-tree {
      padding: 5px;
      height: calc(100% - 100px);
      overflow: hidden;
      .all-goods {
        height: 32px;
        line-height: 32px;
        background: $a11-Color;
        color: white;
        padding-left: 10px;
        font-size: $fontSize-1;
      }
      .tree-height {
        height: calc(100% - 40px);
      }

      .add-goods {
        position: absolute;
        left: 0;
        right: 0;
        bottom: 0;
        height: 40px;
        line-height: 40px;
        font-size: $fontSize-1;
        text-align: center;
        box-shadow: 0 0 2px 3px #ededed;
        cursor: pointer;
        color: $mainColor;
        
        & > span > span {
          padding-left: 5px;
        }
      }
    }

  }
  .right-area {
    // flex: 3;
    width: calc(100% - 240px);
    background: white;
    box-shadow: 2px 2px 5px rgba(233, 230, 230 ,.8), -2px -2px 5px rgba(233, 230, 230 ,.8);
    border-radius: $radius-1;
    padding: 10px;

    .right-area-search {
      line-height: 40px;
      height: 40px;
      padding: 0px 0px 10px 20px;
      display: flex;
    }
    .table {
      height: calc(100% - 120px);
      padding: 0 20px;
      overflow: auto;
    }
    .page {
      height: 40px;
      line-height: 40px;
      background: white;
      margin: 10px 20px 5px;
      text-align: right;
    }
  }
}
}



.node-tree-title {
background: white;
font-size: $fontSize;
color: $mainColor;
}
.opation {
font-size: $fontSize;
padding-left: 30px;
}
.node-isActive {
background: white;
color: $mainColor;
box-shadow: 0 0 5px 2px rgba(17, 185, 208, .3);
border-radius: 4px;
padding: 2px 5px;
}

.tipsOperation {
background: white;
min-width: 100px;
// height: 80px;
box-shadow: 0 2px 4px #ccc;
border-radius: 4px;
position: fixed;
z-index: 99;

.tip-item {
  line-height: 35px;
  // text-align: center;
  cursor: pointer;
  padding-left: 15px;

  & > span {
    font-size: 14px;
    padding-left: 5px;
  }
}
.tip-item:hover {
  background: #e9e9e9;
}
}
</style>